package com.wangjiang.shiro;

import com.wangjiang.model.UserModel;
import com.wangjiang.service.shiro.ShiroService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;

public class MyShiroRealm extends AuthorizingRealm {

    @Resource
    public ShiroService shiroService;
    private static final transient Logger log = LoggerFactory.getLogger(MyShiroRealm.class);


    /**
     * 授权
     */
    //@Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        log.info("======doGetAuthorizationInfo=======");
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        String username = (String) getAvailablePrincipal(principals);
        log.info("======username:"+username+"=======");

        // 这里可以通过数据库拉取权限来实现，下面通过硬代码显现权限
        //权限
        Set<String> s = new HashSet<String>();
        s.add("log:read");
        s.add("log:write");
        authorizationInfo.setStringPermissions(s);
        //角色
        Set<String> r = new HashSet<String>();
        r.add("admin");
        authorizationInfo.setRoles(r);
        return authorizationInfo;
    }

    /**
     * 登录认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取用户账号
        String username = token.getPrincipal().toString();

//        String password = shiroService.getPasswordByUsername(username);
//        if (password != null) {
//            AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
//                    username,   //认证通过后，存放在session,一般存放user对象
//                    password,   //用户数据库中的密码
//                    getName());    //返回Realm名
//            return authenticationInfo;
//        }
        UserModel user = shiroService.getUserByUsername(username);

        if (!ObjectUtils.isEmpty(user)) {

            /**
             * 四个参数
             * principal：认证的实体信息，可以是username，也可以是数据库表对应的用户的实体对象
             * credentials：数据库中的密码（经过加密的密码）
             * credentialsSalt：盐值（使用用户名）
             * realmName：当前realm对象的name，调用父类的getName()方法即可
             */

            String realmName = getName();
            String credentials = user.getPassword();
            ByteSource credentialsSalt = ByteSource.Util.bytes(username);

            return new SimpleAuthenticationInfo(username, credentials, credentialsSalt, realmName);
        }

        return null;
    }
}